/**
 * 
 */
package com.zznode.client.wlanpolling.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * @author Pink
 * ThroughtOuputputRate测试任务
 */
public class ThroughtOuputputRatesExceuteTask implements Runnable {
	private String testAddress;
	private ThroughtOuputputRatesExceuteListener listener;
	private String tag;
	private boolean interrupted = false;
	
	public ThroughtOuputputRatesExceuteTask(String testAddress,
			ThroughtOuputputRatesExceuteListener listener, String tag) {
		this.testAddress = testAddress;
		this.listener = listener;
		this.tag = tag;
	}

	public boolean isInterrupted() {
		return interrupted;
	}

	public void setInterrupted(boolean interrupted) {
		this.interrupted = interrupted;
	}

	@Override
	public void run() {
		// 发起Http请求,测试下载速度
		HttpGet httpGet = new HttpGet(testAddress);

		int totalSize = 0;
		long totalTime = 0;
		long currentTime = 0, lastTime = 0, lastSize = 0;
		long beginTime = 0;
		int count = 0;
		int averageSpeed, peekSpeed = 0;
		
		try {
			HttpResponse response = new DefaultHttpClient().execute(httpGet);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				beginTime = System.currentTimeMillis();
				InputStream is = response.getEntity().getContent();
				
				int val;
				while ((val = is.read()) != -1) {
					totalSize++;
					
					long systemTime = System.currentTimeMillis();
					if(systemTime - currentTime > 1000) {
						count++;
						lastTime = currentTime;
						currentTime = systemTime;
						totalTime = currentTime - beginTime;
						long deltaTime = (systemTime - lastTime)/1000;
						int currentSpeed = 0;
						if(deltaTime > 0) {
							currentSpeed = (int)((totalSize - lastSize) /deltaTime);
						}
						
						if(peekSpeed < currentSpeed) {
							peekSpeed = currentSpeed;
						}
						
						if(totalTime > 1000) {
							averageSpeed = (int)(totalSize/(totalTime/1000));
						} else {
							averageSpeed = 0;
						}
						
						int[] speeds = new int[]{currentSpeed, averageSpeed, peekSpeed}; 
						//notify listener
						if(listener != null) {
							listener.onProgress(tag, totalSize, count, speeds);
						}
						lastSize = totalSize;
						if(interrupted == true)
							break;
					}
				}
				
				totalTime = System.currentTimeMillis() - beginTime;
				long speed = (System.currentTimeMillis() - beginTime) > 1000 ? totalSize/((System.currentTimeMillis() - beginTime)/1000) : 0;
				if(listener != null) {
					listener.onExecuteOver(tag, totalSize, (int)totalTime, (int)speed, null);
				}
			} else {
				if(listener != null) {
					listener.onExecuteOver(tag, 0, 0, 0, new Exception(response.getStatusLine().toString()));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
